﻿using Infrastructure.Access;
using Infrastructure.Operator;
using Infrastructure.SorketOperate;
using Infrastructure.Web;
using MyApplication;
using MyData;
using MyData.Dto;
using MyData.Models;
using MyWeb.App_Start;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace MyWeb.Controllers
{
    public class UserInfoController : BaseController
    {

        // GET: UserInfo
        [HandlerLogin]
        public ActionResult Index()
        {
            if (OperatorProvider.Provider.GetCurrent().DepartId.HasValue)
            {
                ViewBag.Departs = departApp.GetList().Where(c => c.Id == OperatorProvider.Provider.GetCurrent().DepartId.Value).ToList();
            }
            else
            {
                ViewBag.Departs = departApp.GetList();
            }
            return View();
        }
        public ActionResult GetStudents(QueryListModel query, Guid departId, string JobNum, string NickName, int NeedConfirm, int OrderName, int OrderType)
        {
            if (OperatorProvider.Provider.GetCurrent().DepartId.HasValue)
            {
                departId = OperatorProvider.Provider.GetCurrent().DepartId.Value;
            }
            var resultList = userInfoApp.GetUserInfos(query, departId, JobNum, NickName, NeedConfirm, OrderName, OrderType);
            return Json(resultList, JsonRequestBehavior.AllowGet);
        }
        [HandlerLogin]
        public ActionResult UserView(string id)
        {
            ViewBag.Departs = departApp.GetList();
            if (!String.IsNullOrEmpty(id))
            {
                var entity = userInfoApp.GetUserInfo(Guid.Parse(id));
                return View(entity);
            }

            return View(new UserInfoDto());
        }
        private static string imgPath = @"/Attach/Img";
        /// <summary>
        /// 附件上传
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UploadProduct(string fileNamePath, string toFilePath)
        {
            var result = new AjaxResult<String>();
            return base.Try<String>(() =>
            {
                var file = HttpContext.Request.Files[0];
                string fileName = file.FileName;
                string ext = Path.GetExtension(file.FileName).ToLower();
                string name = Guid.NewGuid().ToString().ToLower() + ext;
                string path = $@"{imgPath}/";
                string fullPath = Server.MapPath(path);
                if (!Directory.Exists(fullPath))//创建文件夹
                    Directory.CreateDirectory(fullPath);
                file.SaveAs(fullPath + name);
                //if (FSDK.FSDKE_OK != FSDK.ActivateLibrary("gyYgVWQTSzjiuGB/hH8dKgg0QrrIuhoHdfUCzD9rY+vru3WRZsaezTX6YWj9osdI/cmxY1NSdLkyWuugMPCxUG7/xNLegHLeaUpzVyKpDkaWL8tJIUsIL7xv9bhmgifPbAyTDuxF3VGxXmHkv/L/MStf9kdXV/A1vVvT93QC4vQ="))
                //{
                //    throw new KnownException("人脸引擎失败");
                //}

                //FSDK.InitializeLibrary();
                //FSDKCam.InitializeCapturing();

                //FSDK.CImage image = new FSDK.CImage(fullPath + name);
                //TFacePosition facePosition = image.DetectFace();
                //if (facePosition.w==0)
                //{
                //    System.IO.File.Delete(fullPath + name);
                //    throw new KnownException("未检测到人脸");
                //}
                result.data = path + name;
            }, result);
        }
        [HttpPost]
        public JsonResult SaveUserInfo(UserInfo userInfo)
        {
            return base.Try(() =>
            {
                userInfoApp.Save(userInfo);
            });
        }
        [HttpPost]
        public JsonResult UserInfoDelete(List<Guid> Ids)
        {
            return base.Try(() =>
            {
                userInfoApp.UserInfoDelete(Ids);
            });

        }
        public ActionResult BatchUser(string fileNamePath, string toFilePath)
        {
            return base.Try(() =>
            {
                var file = HttpContext.Request.Files[0];
                string fileName = file.FileName;
                // string fileName = "技术部_潘景树_1011.jpg";
                UserInfo userInfo = GetUserInfoByName(fileName);
                string ext = Path.GetExtension(file.FileName).ToLower();
                string name = Guid.NewGuid().ToString().ToLower() + ext;
                string path = $@"{imgPath}/";
                string fullPath = Server.MapPath(path);
                if (!Directory.Exists(fullPath))//创建文件夹
                    Directory.CreateDirectory(fullPath);
                file.SaveAs(fullPath + name);
                //if (FSDK.FSDKE_OK != FSDK.ActivateLibrary("gyYgVWQTSzjiuGB/hH8dKgg0QrrIuhoHdfUCzD9rY+vru3WRZsaezTX6YWj9osdI/cmxY1NSdLkyWuugMPCxUG7/xNLegHLeaUpzVyKpDkaWL8tJIUsIL7xv9bhmgifPbAyTDuxF3VGxXmHkv/L/MStf9kdXV/A1vVvT93QC4vQ="))
                //{
                //    throw new KnownException("人脸引擎失败");
                //}

                //FSDK.InitializeLibrary();
                //FSDKCam.InitializeCapturing();

                //FSDK.CImage image = new FSDK.CImage(fullPath + name);
                //TFacePosition facePosition = image.DetectFace();
                //if (facePosition.w == 0)
                //{
                //    System.IO.File.Delete(fullPath + name);
                //    throw new KnownException("未检测到人脸");
                //}
                userInfo.HeadUrl = path + name;
                userInfoApp.Save(userInfo);
            });
        }
        private UserInfo GetUserInfoByName(string fileName)
        {

            fileName = fileName.Substring(0, fileName.IndexOf('.'));
            string[] array = fileName.Split('_');
            UserInfo userInfo = new UserInfo();
            if (PublicInfo.Version != (int)EnumVersion.太白)
            {
                Guid? departId = departApp.GetDepartByName(array[0]);
                if (!departId.HasValue)
                    throw new KnownException(fileName + "部门命名错误");
                userInfo.WorkNum = array[2];
                userInfo.NickName = array[1];
            }
            else
            {
                if (array.Length != 1)
                    throw new KnownException(fileName + "文件命名错误");
                userInfo.NickName = array[0];
            }
            int sex = 1;
            userInfo.Sex = Convert.ToInt32(array[2]);
            //userInfo.DepartId = departId.Value;
            userInfo.RoleName = "";
            userInfo.PhoneNum = "";
            userInfo.CardNum = "";
            int age = 0;
            userInfo.Age = age;
            userInfo.Nation = "";
            userInfo.Address = "";
            return userInfo;
        }
        [HttpPost]
        public JsonResult SynsUser()
        {
            return base.Try(() =>
            {
                userInfoApp.SynsUserSend(1);
                string sql2 = string.Format("OK");
                string recvStr = SorketClient.SendSql(sql2);
            });
        }
        [HttpPost]
        public JsonResult QueryUserInfo(string WorkNum)
        {
            var result = new AjaxResult<String>();
            return base.Try<string>(() =>
            {
                string sql2 = string.Format("1;SELECT NAME FROM USERINFO WHERE Badgenumber = '{0}'", WorkNum);
                string recvStr = SorketClient.SendSql(sql2);
                if (recvStr.Length == 0)
                {
                    throw new KnownException("未查到匹配人员");
                }
                result.data = recvStr;


            }, result);
        }
        public JsonResult ConfirmUserInfo(Guid Id)
        {
            return base.Try(() =>
            {
                userInfoApp.ConfirmUser(Id);
            });
        }
    }
}
